const isLogin = () => {
    const node_show =
        id("pro.huobi:id/total_balance_show").getOneNodeInfo(3 * 1000);
    return !!node_show;
}

const login = (timeout, data) => {
    const node_login =
        id("pro.huobi:id/main_balance_tab").getOneNodeInfo(timeout);
    node_login.click();
    if (isLogin()) {
        return;
    }
    const node_account =
        id("pro.huobi:id/login_account_edit").getOneNodeInfo(timeout);
    node_account.inputText(data.coin_account);
    const node_pwd =
        id("pro.huobi:id/login_psw_edit").getOneNodeInfo(timeout);
    node_pwd.inputText(data.coin_pwd);
    const node_login_btn =
        id("pro.huobi:id/login_btn").getOneNodeInfo(timeout);
    node_login_btn.click();
    sleep(3000);
}

const searchCoin = (timeout, data) => {
    const node_tab =
        id("pro.huobi:id/main_market_tab").getOneNodeInfo(timeout);
    node_tab.click();
    const node_search =
        id("pro.huobi:id/market_markets_search").getOneNodeInfo(timeout);
    node_search.click()
    const node_input =
        id("pro.huobi:id/search_symbol_input").getOneNodeInfo(timeout);
    node_input.inputText(data.coin_name);
    const node_res =
        id("pro.huobi:id/item_search_symbol_result").text(data.coin_name + "/USDT").getOneNodeInfo(timeout);
    node_res.click();
}

const loginValidation = (timeout) => {
    if (isLogin()) {
        return;
    }
    const request = image.requestScreenCapture(timeout, 0);
    if (request) {
        toast("申请成功");
    } else {
        toast("申请失败");
        exit();
    }
    //申请完权限等1s再截图,否则会截不到图
    sleep(1000);
    //从工程目录下res文件夹下读取文件
    const sms1 = readResAutoImage("ec-656.png");
    const sms2 = readResAutoImage("ec-613.png");
    //在当前屏幕中查找，并且限制只查找一个
    const points1 = image.findImageEx(sms1, 0, 0, 0, 0, 0.7, 1);
    const points2 = image.findImageEx(sms2, 0, 0, 0, 0, 0.7, 1);
    if (points1 && points2) {
        const startCenter = points1[0].center();
        const endCenter = points2[0].center();
        swipeToPoint(startCenter.x, startCenter.y, endCenter.x, endCenter.y, 1000);
        sleep(3000);
    }
}

const buyCoin = (timeout, data) => {
    const node_buy =
        id("pro.huobi:id/market_buy").getOneNodeInfo(timeout);
    node_buy.click();
    //获取当前价格
    const selectors = id("pro.huobi:id/price_convert_tv");
    if (waitExistNode(selectors, timeout)) {
        const node_price_cny = selectors.getOneNodeInfo(timeout);
        //去掉小数 ≈364122.30 CNY
        const pattern = /\d+\.\d+/g;
        const price_tmp = node_price_cny.text.match(pattern)[0];
        const price = parseInt(price_tmp.split(".")[0]);
        //根据定投金额换算btc数量
        const price_cny = parseInt(data.coin_cny);
        const input_price = price_cny / price;
        const node_input =
            id("pro.huobi:id/input_amount_et").getOneNodeInfo(timeout);
        node_input.inputText(input_price.toString())
        //买入
        const node_buy_btn =
            id("pro.huobi:id/btn_trade_confirm").getOneNodeInfo(timeout);
        node_buy_btn.click();
    }
}

const autoServiceStart = (time) => {
    for (let i = 0; i < time; i++) {
        if (isServiceOk()) {
            return true;
        }
        const started = startEnv();
        showLog("第" + (i + 1) + "次启动服务结果: " + started);
        if (isServiceOk()) {
            return true;
        }
    }
    return isServiceOk();
}

const isStart = (data) => {
    const currentDate = new Date();
    const weekDay = currentDate.getDay().toString();
    const hours = currentDate.getHours() > 9 ? currentDate.getHours() : '0' + currentDate.getHours();
    const minutes = currentDate.getMinutes() > 9 ? currentDate.getMinutes() : '0' + currentDate.getMinutes();
    const timeStr = hours + ':' + minutes;
    return !!(data[weekDay] && timeStr === data.coin_time);
}

const getConfigData = () => {
    ui.clearAllShareData();
    ui.saveAllConfig();
    const dataStr = ui.getConfigJSON();
    return JSON.parse(dataStr);
}

const autoCoin = () => {
    const data = getConfigData();
    const timeout = 30 * 1000;

    //判断当前时间是否在定投计划时间
    showLog("开始一个循环");
    showLog("校验时间");
    if (isStart(data)) {
        agentEvent.lightScreen();
        showLog("开始定投");
        //登入
        login(timeout, data);

        //安全验证
        loginValidation(timeout);

        //找币
        searchCoin(timeout, data);

        //买币
        buyCoin(timeout, data);
        showLog("结束定投");
        agentEvent.closeScreen();
        //等待时间，防止当前时间再次定投
        sleep(60 * 1000);
    } else {
        agentEvent.closeScreen();
    }
    showLog("结束一个循环");
}

const showLog = (msg) => {
    setLogText(msg + timeFormat("HH:mm:ss"), "#ffffff", 14);
    // logd(msg + timeFormat("HH:mm:ss"));
}

const main = () => {
    //1 代理模式 2 无障碍模式
    // ui.setRunningMode(1);
    showLogWin();
    if (!autoServiceStart(3)) {
        showLog("自动化服务启动失败，无法执行脚本")
        exit();
        return;
    }
    //根据应用包名打开火币APP
    const isOpen = utils.openApp("pro.huobi");
    toast("30秒后开始运行，等待火币APP启动完成");
    showLog("30秒后开始运行，等待火币APP启动完成");
    sleep(30 * 1000);
    while (isOpen) {
        try {
            showLog("检测心跳");
            //自动定投
            autoCoin();
            //建议30s检测一次
            sleep(1000 * 30);
        } catch (e) {
            showLog("出错了" + e);
        }
    }
}

main();